from flask import request, jsonify

from tzq.document_management_system import dms_bp
from tzq.document_management_system.model.log_model import Log


# layui多条件分页查询接口
@dms_bp.route('/api/log', methods=['GET'])
def get_log():
    page = int(request.args.get('page', 1))
    limit = int(request.args.get('limit', 10))

    # 获取搜索参数
    business_type = request.values.get("business_type")
    log_type = request.values.get("log_type")
    ip = request.values.get("ip")
    field_name = request.values.get("field_name")
    old_value = request.values.get("old_value")
    new_value = request.values.get("new_value")
    print("business_type=", business_type)
    # 基础查询
    query = Log.query

    # 应用搜索条件
    if business_type:
        query = query.filter(Log.business_type.ilike(f'%{business_type}%'))
    if log_type:
        query = query.filter(Log.log_type == f'{log_type}')
    if ip:
        query = query.filter(Log.ip.ilike(f'%{ip}%'))
    if field_name:
        query = query.filter(Log.field_name.ilike(f'%{field_name}%'))
    if old_value:
        query = query.filter(Log.old_value.ilike(f'%{old_value}%'))
    if new_value:
        query = query.filter(Log.new_value.ilike(f'%{new_value}%'))

    # 排序
    # 获取排序参数
    sort_field = request.args.get('field', 'log_id')
    sort_order = request.args.get('order', 'desc')

    # 构建排序
    if hasattr(Log, sort_field):
        if sort_order == 'asc':
            order_by = getattr(Log, sort_field).asc()
        else:
            order_by = getattr(Log, sort_field).desc()
        query = query.order_by(order_by)
    else:
        query = query.order_by(Log.log_id.desc())
    # query = query.order_by(Log.log_id.desc())

    # 分页查询
    pagination = query.paginate(page=page, per_page=limit, error_out=False)

    # 构建Layui要求的JSON格式
    return jsonify({
        'code': 0,
        'msg': '',
        'count': pagination.total,
        'data': [dataInfo.to_dict() for dataInfo in pagination.items]
    })
